package com.hzncc.flowable_diboot.contract.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.conditions.query.LambdaQueryChainWrapper;
import com.diboot.core.controller.BaseCrudRestController;
import com.diboot.core.util.V;
import com.diboot.core.vo.JsonResult;
import com.diboot.core.vo.Pagination;
import com.diboot.iam.annotation.BindPermission;
import com.diboot.iam.annotation.Log;
import com.diboot.iam.annotation.OperationCons;
import com.hzncc.flowable_diboot.contract.dto.ContractAuditUpdateDTO;
import com.hzncc.flowable_diboot.contract.entity.ContractAudit;
import com.hzncc.flowable_diboot.contract.entity.ContractAuditUpdate;
import com.hzncc.flowable_diboot.contract.service.ContractAuditService;
import com.hzncc.flowable_diboot.contract.service.ContractAuditUpdateService;
import com.hzncc.flowable_diboot.contract.vo.ContractAuditUpdateDetailVO;
import com.hzncc.flowable_diboot.contract.vo.ContractAuditUpdateListVO;
import com.hzncc.flowable_diboot.contract.vo.ContractAuditVO;
import com.hzncc.flowable_diboot.contract.vo.ContractProductListVO;
import com.hzncc.flowable_diboot.enums.ContractAuditStatusEnum;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 合同变更 相关rest接口
 *
 * @author MyName
 * @version 1.0
 * @date 2024-08-20
 * Copyright © MyCorp
 */
@Slf4j
@RequestMapping("/contract-audit-update")
@BindPermission(name = "合同变更")
@RestController
public class ContractAuditUpdateController extends BaseCrudRestController<ContractAuditUpdate> {

    @Autowired
    private ContractAuditUpdateService contractAuditUpdateService;

    @Autowired
    private ContractAuditService contractAuditService;

    /**
     * 查询资源对象的列表VO记录
     * <p>
     * url请求参数示例: ?fieldA=abc&pageSize=20&pageIndex=1&orderBy=id
     * </p>
     *
     * @return
     * @throws Exception
     */
    @Log(operation = OperationCons.LABEL_LIST)
    @BindPermission(name = OperationCons.LABEL_LIST, code = OperationCons.CODE_READ)
    @GetMapping()
    public JsonResult<List<ContractAuditUpdateListVO>> getListVOMapping(ContractAuditUpdateDTO queryDto, Pagination pagination) throws Exception {
        LambdaQueryChainWrapper<ContractAudit> lq = contractAuditService.lambdaQuery();
        lq.select(ContractAudit::getId)
                .ne(ContractAudit::getContractStatus, ContractAuditStatusEnum.HISTORY.getCode())
                .ne(ContractAudit::getContractStatus, ContractAuditStatusEnum.NO_SUBMIT.getCode());
        List<ContractAudit> entityList = contractAuditService.getEntityList(lq);
        QueryWrapper<ContractAuditUpdateDTO> queryWrapper = super.buildQueryWrapperByDTO(queryDto);
        if (pagination != null && V.isEmpty(pagination.getOrderBy())) {
            pagination.setOrderBy(Pagination.ORDER_BY_ID_DESC);
        }
        if (entityList != null && !entityList.isEmpty()) {
            queryWrapper.lambda().in(ContractAuditUpdate::getContractAuditId, entityList.stream().map(ContractAudit::getId).collect(Collectors.toList()));
        }
        queryWrapper.select("contract_audit_id");
        List<ContractAuditUpdate> voList = this.getService().getEntityList(queryWrapper,pagination);
        return contractAuditService.selectContractUpdateDetailList(voList).bindPagination(pagination);
    }

    /**
     * 根据id查询资源对象的详情VO
     *
     * @param id ID
     * @return
     * @throws Exception
     */
    @Log(operation = OperationCons.LABEL_DETAIL)
    @BindPermission(name = OperationCons.LABEL_DETAIL, code = OperationCons.CODE_READ)
    @GetMapping("/{id}")
    public JsonResult<ContractAuditUpdateDetailVO> getDetailVOMapping(@PathVariable("id") String id) throws Exception {
        ContractAuditUpdateDetailVO detailVO = contractAuditUpdateService.getViewObject(id, ContractAuditUpdateDetailVO.class);
        return JsonResult.OK(detailVO);
    }


    /**
     * 创建资源对象数据
     *
     * @param contractAuditUpdate
     * @return JsonResult
     * @throws Exception
     */
    @Log(operation = OperationCons.LABEL_CREATE)
    @BindPermission(name = OperationCons.LABEL_CREATE, code = OperationCons.CODE_WRITE)
    @PostMapping()
    public JsonResult<?> createModelMapping(@RequestBody ContractAuditUpdate contractAuditUpdate) throws Exception {
        boolean success = contractAuditUpdateService.createEntity(contractAuditUpdate);
        log.debug("新建数据 合同变更:{} {}", contractAuditUpdate.getId(), success ? "成功" : "失败");
        return JsonResult.OK(contractAuditUpdate.getId());
    }

    /**
     * 批量创建资源对象数据
     *
     * @param contractAuditUpdateList
     * @return JsonResult
     * @throws Exception
     */
    @Log(operation = OperationCons.LABEL_BATCH_UPDATE)
    @BindPermission(name = OperationCons.LABEL_UPDATE, code = OperationCons.CODE_WRITE)
    @PostMapping("/batch")
    public JsonResult<?> batchCreateModelMapping(@RequestBody List<ContractAuditUpdate> contractAuditUpdateList) throws Exception {
        boolean success = contractAuditUpdateService.createEntities(contractAuditUpdateList);
        log.debug("批量新建数据 合同变更 {}", success ? "成功" : "失败");
        return JsonResult.OK(success);
    }

    /**
     * 根据id更新资源对象
     *
     * @param contractAuditUpdate
     * @return JsonResult
     * @throws Exception
     */
    @Log(operation = OperationCons.LABEL_UPDATE)
    @BindPermission(name = OperationCons.LABEL_UPDATE, code = OperationCons.CODE_WRITE)
    @PutMapping("/{id}")
    public JsonResult<?> updateModelMapping(@PathVariable("id") String id, @RequestBody ContractAuditUpdate contractAuditUpdate) throws Exception {
        boolean success = contractAuditUpdateService.updateEntity(contractAuditUpdate);
        log.debug("更新数据 合同变更:{} {}", id, success ? "成功" : "失败");
        return JsonResult.OK(success);
    }

    /**
     * 根据id删除资源对象
     *
     * @param id
     * @return
     * @throws Exception
     */
    @Log(operation = OperationCons.LABEL_DELETE)
    @BindPermission(name = OperationCons.LABEL_DELETE, code = OperationCons.CODE_WRITE)
    @DeleteMapping("/{id}")
    public JsonResult<?> deleteModelMapping(@PathVariable("id") String id) throws Exception {
        boolean success = contractAuditUpdateService.deleteEntity(id);
        log.debug("删除数据 合同变更:{} {}", id, success ? "成功" : "失败");
        return JsonResult.OK(success);
    }

    /**
     * 根据ids集合删除资源对象
     *
     * @param ids
     * @return
     * @throws Exception
     */
    @Log(operation = OperationCons.LABEL_BATCH_DELETE)
    @BindPermission(name = OperationCons.LABEL_DELETE, code = OperationCons.CODE_WRITE)
    @PostMapping("/batch-delete")
    public JsonResult<?> deleteEntityMapping(@RequestBody List<String> ids) throws Exception {
        boolean success = contractAuditUpdateService.deleteEntities(ids);
        log.debug("批量删除数据 合同变更:{} {}", ids, success ? "成功" : "失败");
        return JsonResult.OK(success);
    }

    /**
     * 获取合同变更
     *
     * @param id 合同评审id
     * @return
     * @throws Exception
     */
    @Log(operation = OperationCons.LABEL_DETAIL)
    @BindPermission(name = OperationCons.LABEL_DETAIL, code = OperationCons.CODE_READ)
    @GetMapping("/updateSaved/{id}")
    public JsonResult<ContractAuditVO> getUpdateDetail(@PathVariable("id") String id) throws Exception {
        // 获取当前合同评审详情
        ContractAuditVO orginContractAudit = contractAuditService.getViewObject(id, ContractAuditVO.class);
        Long contractVersion = orginContractAudit.getContractVersion();
        // 获取暂存的合同评审
        QueryWrapper<ContractAudit> qw = new QueryWrapper<>();
        qw.lambda().eq(ContractAudit::getContractCode, orginContractAudit.getContractCode())
                .eq(ContractAudit::getContractVersion, contractVersion + 1)
                .eq(ContractAudit::getContractStatus, ContractAuditStatusEnum.NO_SUBMIT.getCode());
        // 暂存合同评审
        ContractAuditVO temp = contractAuditService.getViewObject(qw, ContractAuditVO.class);
        if (temp == null) { // 如果暂存合同评审不存在，则使用原合同评审
            temp = orginContractAudit;
            temp.setContractAuditUpdateVO(new ContractAuditUpdateDetailVO());
        } else { // 如果暂存合同评审存在，则使用暂存合同评审
            temp.setContractStatus(orginContractAudit.getContractStatus());
            List<ContractProductListVO> tempList = temp.getContractProductVOList();
            List<ContractProductListVO> orList = orginContractAudit.getContractProductVOList();
            // 预处理：创建快速查找的映射关系
            Map<String, ContractProductListVO> orMap = new HashMap<>();
            for (ContractProductListVO orItem : orList) {
                if (orItem.getSapContractId() != null) {
                    orMap.put(orItem.getSapContractId(), orItem);
                }
            }
            for (ContractProductListVO contractProductListVO : tempList) {
                String currentId = contractProductListVO.getSapContractId();
                if (currentId != null) {
                    ContractProductListVO matchedOrItem = orMap.get(currentId);
                    if (matchedOrItem != null) {
                        contractProductListVO.setSapContractPushStatus(matchedOrItem.getSapContractPushStatus());
                        contractProductListVO.setSapContractCode(matchedOrItem.getSapContractCode());
                    }
                }
            }
        }
        return JsonResult.OK(temp);
    }

    /**
     * 比较合同变更
     *
     * @param id 合同id
     * @return
     * @throws Exception
     * @author 陈广煜
     * @date 2024-08-21
     */
    @Log(operation = OperationCons.LABEL_DETAIL)
    @BindPermission(name = OperationCons.LABEL_DETAIL, code = OperationCons.CODE_READ)
    @GetMapping("/compare/{id}")
    public JsonResult<?> compare(@PathVariable("id") String id) throws Exception {
        return JsonResult.OK(contractAuditService.getDiff(id));
    }

    /**
     * 比较合同变更
     *
     * @param id 合同id
     * @return
     * @throws Exception
     * @author 陈广煜
     * @date 2024-08-21
     */
    @Log(operation = OperationCons.LABEL_DETAIL)
    @BindPermission(name = OperationCons.LABEL_DETAIL, code = OperationCons.CODE_READ)
    @PostMapping("/compare/{id}")
    public JsonResult<?> compare(@PathVariable("id") String id, @RequestBody List<ContractProductListVO> contractProductVOList) throws Exception {
        return JsonResult.OK(contractAuditService.getDiff(id, contractProductVOList));
    }

    /**
     * 比较合同产品项目变更
     *
     * @param id 合同id
     * @return
     * @throws Exception
     * @author 陈广煜
     * @date 2024-08-23
     */
    @Log(operation = OperationCons.LABEL_DETAIL)
    @BindPermission(name = OperationCons.LABEL_DETAIL, code = OperationCons.CODE_READ)
    @GetMapping("/compareProduct/{id}")
    public JsonResult<?> compareProduct(@PathVariable("id") String id) throws Exception {
        return JsonResult.OK(contractAuditService.getProductDiff(id));
    }

    /**
     * 比较合同产品项目变更
     *
     * @param id 合同id
     * @return
     * @throws Exception
     * @author 陈广煜
     * @date 2024-08-23
     */
    @Log(operation = OperationCons.LABEL_DETAIL)
    @BindPermission(name = OperationCons.LABEL_DETAIL, code = OperationCons.CODE_READ)
    @PostMapping("/compareProduct/{id}")
    public JsonResult<?> compareProduct(@PathVariable("id") String id, @RequestBody List<ContractProductListVO> contractProductVOList) throws Exception {
        return JsonResult.OK(contractAuditService.getProductDiff(id, contractProductVOList));
    }
}